/**
 * @(#) ReqCelebrationMediator.as
 *
 * @date		2010. 11. 01
 * @version		2.0
 * @author		Shin, Yunwoo
 * @client		Service Ace
 * @module		CongMoney  (경조금)
 * @description	경조금 신청 - Mediator
 *
 */
package com.skt.common_hr.schoolexp_nos.view
{
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.CommonMediator;
	import com.skt.common_hr.schoolexp_nos.events.FamilyEvent;
	import com.skt.common_hr.schoolexp_nos.model.AccountProxy;
	import com.skt.common_hr.schoolexp_nos.model.AttachFileSchoolExpProxy;
	import com.skt.common_hr.schoolexp_nos.model.FamilyProxy;
	import com.skt.common_hr.schoolexp_nos.model.SchoolExpProxy;
	import com.skt.common_hr.schoolexp_nos.model.vo.AccountVO;
	import com.skt.common_hr.schoolexp_nos.model.vo.FamilyVO;
	import com.skt.common_hr.schoolexp_nos.model.vo.ReqSchoolExpVO;
	import com.skt.common_hr.schoolexp_nos.model.vo.SchoolExpFileUpLoadVO;
	import com.skt.common_hr.schoolexp_nos.model.vo.SchoolExpVO;
	import com.skt.common_hr.schoolexp_nos.view.components.FamilyViewNos;
	import com.skt.common_hr.schoolexp_nos.view.components.ReqSchoolExpView;
	import com.wcl.utils.DateUtil;
	import com.wcl.utils.StringUtil;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;

	public class ReqSchoolExpMediator extends CommonMediator
	{
		public static const NAME:String = "ReqSchoolExpMediator";

		public static const INIT_REQ_SCHOOLEXP:String 	= "initReqSchoolExp";
		public static const MODIFY_REQ_SCHOOLEXP:String	= "modifyReqSchoolExp";
		public static const READONLY_REQ_SCHOOLEXP:String	= "readonlyReqSchoolExp";

		public static const CLOSED_REQUEST_VIEW:String	= "closedRequestView";


 		private var bWaitingApproval:Boolean = false;
 		private var bWaitingExistData:Boolean = false;
		private var _currentKey:String = "";


		/**
		* 생성자
		*
		* @param
		* @return void
		*/
        public function ReqSchoolExpMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
        }

		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		override protected function initializeView():void
 		{
 			orgFileName = "";
 			setEventListeners();
 			loadBankAccount();
 			loadFamilyInfo();
 		}

 		private function setEventListeners():void
 		{
 			view.addEventListener(ReqSchoolExpView.CLICK_PREV_SCREEN, onClickPrervScreen);
 			view.addEventListener(ReqSchoolExpView.CLICK_REQUEST, onClickRequest);
 			view.addEventListener(ReqSchoolExpView.ADD_MEMBER, onAddMember);
 			view.addEventListener(ReqSchoolExpView.DEL_MEMBER, onDelMember);
 			
			view.addEventListener(ReqSchoolExpView.NoticeOnlyFileDelete, onNoticeOnlyFileDelete);
			//view.addEventListener(ReqSchoolExpView.NoticeDelete, onNoticeDelete);
			view.addEventListener(ReqSchoolExpView.GetFile, onBrowseFile); 			
 		}
 		
 		// 파일추가
		private function onBrowseFile(event:Event):void
		{
			var proxy:AttachFileSchoolExpProxy = facade.retrieveProxy(AttachFileSchoolExpProxy.NAME) as AttachFileSchoolExpProxy;
			proxy.browse();
		}
		
		//파일삭제
		private function onNoticeOnlyFileDelete(event:Event):void
		{
			view.fileName = "";
			fileInfo = new SchoolExpFileUpLoadVO();
		}
		
 		override protected function clearView():void
 		{
 			trace("clear CongMoneyWriteMediator");
 		}


 		private function initViewData(type:String):void
 		{
 			view.dept  = Variables.myOrg;
 			view.pernr = Variables.myPernr;
 			view.ename = Variables.myName;
 			//view.tel   = Variables.my
 			view.reqList = new ArrayCollection();
 			view.selectedReqType = "00";
 			_currentKey = "";

			view.modeReadOnly = (type==READONLY_REQ_SCHOOLEXP) ? true : false;
			
			if(type==INIT_REQ_SCHOOLEXP) {
				view.modeReadOnly2 = true;
			} else {
				view.modeReadOnly2 = false;
			}
 		}

		private function setViewData(proxy:SchoolExpProxy):void
 		{
 			var arr:ArrayCollection = new ArrayCollection();

 			for each(var vo:SchoolExpVO in proxy.schoolExpList) {
 				var tmp:ReqSchoolExpVO = new ReqSchoolExpVO();
 				tmp.FAMSA = vo.FAMSA;
 				tmp.FCNAM = vo.FCNAM;
 				tmp.REGNO = vo.REGNO;
 				tmp.TOTPY = vo.TOTPY;
 				tmp.ZCOUMS = vo.ZCOUMS;
 				tmp.ZGRADE = vo.ZGRADE;
 				tmp.ZOLD = vo.ZOLD;
 				tmp.ZSLART = vo.ZSLART;
 				tmp.ZYEAR = vo.ZYEAR.toString();
 				tmp.ZFDATE = new Date(vo.ZFDATE);
 				tmp.ZTDATE = new Date(vo.ZTDATE);

 				tmp.ZFYEAR = tmp.ZFDATE.fullYear.toString();
 				tmp.ZFMONTH = (tmp.ZFDATE.month+1).toString();
 				tmp.ZTYEAR = tmp.ZTDATE.fullYear.toString();
 				tmp.ZTMONTH = (tmp.ZTDATE.month+1).toString();

	 			_currentKey = vo.WEL_KEY01;
	 			view.selectedReqType = vo.SLART;
 				arr.addItem(tmp);
 			}
 			view.reqList = arr;
 			view.fileList = proxy.schoolExpFile;
 			orgFileName = view.fileList.I_FILE_NAME;
 		}


 		private function loadDetailData(key:String):void
 		{
 			var proxy:SchoolExpProxy = facade.retrieveProxy(SchoolExpProxy.NAME) as SchoolExpProxy;
 			proxy.load(key);
 		}

 		private function loadBankAccount():void
 		{
 			var proxy:AccountProxy = facade.retrieveProxy(AccountProxy.NAME) as AccountProxy;
 			proxy.load(Variables.myPernr);
 		}

  		private function loadFamilyInfo():void
 		{
 			var proxy:FamilyProxy = facade.retrieveProxy(FamilyProxy.NAME) as FamilyProxy;
 			proxy.load(Variables.myPernr);
 		}

		private function onClickPrervScreen(e:Event):void
 		{
 			view.fileList = new SchoolExpFileUpLoadVO();
 			view.fileName = '';
 			fileInfo = new SchoolExpFileUpLoadVO();
 			
 			view.modeReadOnly = false; 			
 			facade.sendNotification(CLOSED_REQUEST_VIEW);
  		}


		// 첨부파일 완료 후 .. 
 		private var _bWaitingSave:Boolean = false;	
 		private var orgFileName:String = "";
		private function onClickRequest(e:Event):void 
 		{
 			if(validate()) { 
	 			if(StringUtil.NVL(view.fileName)!="" && StringUtil.NVL(view.fileName)!=StringUtil.NVL(orgFileName)) {
	 			//if(view.modeReadOnly==false)
	 				_bWaitingSave = true;
					var proxy:AttachFileSchoolExpProxy = facade.retrieveProxy(AttachFileSchoolExpProxy.NAME) as AttachFileSchoolExpProxy;
					proxy.uploadFile();
					// upload가 있을시에는...  upload후에.. save 부름. 
	 			}
	 			else {
	 				if(StringUtil.NVL(orgFileName)!="" && StringUtil.NVL(view.fileName)!=StringUtil.NVL(orgFileName)) {
	 					//deleteFile();  하는짓 없음
	 				}
	 				fileInfo = view.fileList;
	 				onClickRequest_proc();
	 			}
 			}
  		}

		private function onClickRequest_proc():void 
 		{
 			_bWaitingSave = false;
 			var vo:SchoolExpFileUpLoadVO = new SchoolExpFileUpLoadVO();
 			if(fileInfo!=null) {
	 			vo.I_FILE_NAME		= fileInfo.I_FILE_NAME;
	 			vo.I_FILE_EXT		= fileInfo.I_FILE_EXT;
	 			vo.I_FILE_URL		= fileInfo.I_FILE_URL;
	 			vo.I_FILE_SIZE		= fileInfo.I_FILE_SIZE;
	 		} else {
	 			vo.I_FILE_NAME		= "";
	 			vo.I_FILE_EXT		= ""; 
	 			vo.I_FILE_URL		= "";
	 			vo.I_FILE_SIZE		= 0;	 			
	 		}
	 		
	 		if(isNaN(vo.I_FILE_SIZE) == true ) {
	 			vo.I_FILE_SIZE = 0;
	 		}
	 		 			
 			var proxy:SchoolExpProxy = facade.retrieveProxy(SchoolExpProxy.NAME) as SchoolExpProxy;
 			proxy.save(_currentKey, Variables.myPernr, view.selectedReqType, buildTable(), vo);
  		}  		

 		private function validate():Boolean
 		{
 			var bRet:Boolean = true;
 			var types:String = "01,02";		// 적용기간을 체크하는 신청구분 코드들..
 			if(view.selectedReqType=="00") {
 				CommonAlert.showMessage("", "신청구분을 정확하게 입력하십시오.", null, "확인");
 				bRet = false;
 			}
 			if(view.reqList.length<1) {
 				CommonAlert.showMessage("", "인적사항을 1건이상 입력하십시오", null, "확인");
 				bRet = false;
 			}

			if(view.selectedReqType=="03" || view.selectedReqType=="04") {
				if(view.fileName == null || view.fileName == '' ) {
					CommonAlert.showMessage("", "첨부파일을 추가하셔야 합니다.", null, "확인");
					bRet = false;
				}
			}
	
			for each(var vo:ReqSchoolExpVO in view.reqList) {
				if(types.indexOf(view.selectedReqType)>=0) {
					var fromYear:int = parseInt(vo.ZFYEAR);
					var fromMonth:int = parseInt(vo.ZFMONTH);
					if(isNaN(fromYear) || fromYear<2000 || fromYear>2100 || isNaN(fromMonth) || fromMonth<1 || fromMonth>12) {
		 				CommonAlert.showMessage("", "적용기간을 정확하게 입력하십시오", null, "확인");
		 				bRet = false;
		 				break;
					}
					vo.ZFDATE = new Date(fromYear, fromMonth-1, 1);

					var toYear:int = parseInt(vo.ZTYEAR);  
					var toMonth:int = parseInt(vo.ZTMONTH);
					if(isNaN(toYear) || toYear<2000 || toYear>2100 || isNaN(toMonth) || toMonth<1 || toMonth>12) {
		 				CommonAlert.showMessage("", "적용기간을 정확하게 입력하십시오", null, "확인");
		 				bRet = false;
		 				break;
					}
					vo.ZTDATE = new Date(toYear, toMonth-1, 1);
					vo.ZTDATE.month ++;
					vo.ZTDATE.date--;

					if(Number(vo.ZFDATE)>Number(vo.ZTDATE)) {
		 				CommonAlert.showMessage("", "적용기간을 정확하게 입력하십시오", null, "확인");
		 				bRet = false;
		 				break;
					}
					vo.TOTPY = 100000;
				}
				else {
					if(vo.TOTPY <=0) {
		 				CommonAlert.showMessage("", "신청금액을 입력하십시오", null, "확인");
		 				bRet = false;
		 				break;
					}
				}
 			}
 			return bRet;
 		}

		private function buildTable():Array
		{
			var table:Array = new Array;
			for each(var vo:ReqSchoolExpVO in view.reqList) {
				var tmp:Object = new Object();

				tmp.FAMSA = vo.FAMSA;
				tmp.FCNAM = vo.FCNAM;
				tmp.REGNO = vo.REGNO;
				tmp.ZOLD = 1;//vo.ZOLD;
				tmp.ZFDATE = DateUtil.toBasicString(vo.ZFDATE);
				tmp.ZTDATE = DateUtil.toBasicString(vo.ZTDATE);
				tmp.ZYEAR = parseInt(vo.ZYEAR);
				tmp.ZGRADE = vo.ZGRADE;
				tmp.ZCOUMS = vo.ZCOUMS;
				tmp.ZSLART = vo.ZSLART;
				tmp.TOTPY = Number(vo.TOTPY/100);
				table.push(tmp);
				//CommonAlert.showMessage("", "신청금액: " + tmp.TOTPY, null, "확인");
			}
			return table;
		}

		private var popFamilyView:FamilyViewNos = null;;
		private function onAddMember(e:Event):void
		{
			if(view.cbReqType.selectedIndex == 0) {
				Alert.show('신청구분을 선택하셔야 합니다.');
				return;
			}
			if(view.reqList.length > 0) {
				Alert.show('한 건씩 처리만 가능합니다 .');
				return;				
			}
			
			var familyProxy:FamilyProxy = facade.retrieveProxy(FamilyProxy.NAME) as FamilyProxy;
			if(popFamilyView==null) {
				popFamilyView = PopUpManager.createPopUp(view, FamilyViewNos, true) as FamilyViewNos;
				PopUpManager.centerPopUp(popFamilyView);
				popFamilyView.addEventListener(FamilyEvent.FAMILY_INFO, onSelectedFamily);
			}
			else {
				PopUpManager.addPopUp(popFamilyView, view, true);
			}

			popFamilyView.familyList = familyProxy.family;
		}

 		private function onDelMember(e:Event):void
 		{
			for(var i:int=0; i<view.reqList.length; i++) {
				var vo:ReqSchoolExpVO = view.reqList.getItemAt(i) as ReqSchoolExpVO;
				if(vo.selected) {
					view.reqList.removeItemAt(i);
					i--;
				}
			}
 		}

 		private function onSelectedFamily(e:FamilyEvent):void
 		{
 			var selectedFamily:FamilyVO = e.target.selectedItem;
			if(!isExistMember(selectedFamily.REGNO)) {
	 			var vo:ReqSchoolExpVO = new ReqSchoolExpVO();
	 			vo.FAMSA = selectedFamily.KDSVH;
	 			vo.FCNAM = selectedFamily.FNAME;
	 			vo.REGNO = selectedFamily.REGNO;
	 			vo.ZOLD = computeAge(vo.REGNO);
	 			view.reqList.addItem(vo);
	 			popFamilyView.closePopUp();
	 		}
	 		else {
	 			CommonAlert.showMessage("", "같은 가족을 이중으로 신청할 수 없습니다.");
	 		}
		}

		private function isExistMember(regno:String):Boolean
		{
			for each(var vo:ReqSchoolExpVO in view.reqList) {
				if(regno==vo.REGNO) return true;
			}
			return false;
		}



 		private function computeAge(regNo:String):int
 		{
 			var year:Number = parseInt(regNo.substr(0, 2));
 			var month:Number = parseInt(regNo.substr(2,2));
 			var date:Number = parseInt(regNo.substr(4,2));

 			var today:Date  = new Date();
 			var age:int = 0;

 			if(year<=(today.fullYear-20000)) {
 				year += 2000;
 			}
 			else {
 				year += 1900;
 			}

 			age = today.fullYear - year;
 			return age;
 		}
 		
		private function onSelectedFile():void
		{
			var proxy:AttachFileSchoolExpProxy = facade.retrieveProxy(AttachFileSchoolExpProxy.NAME) as AttachFileSchoolExpProxy;
			view.fileName = proxy.fileVo.I_FILE_NAME;
		} 		
		
		private function onProgressUpload(proxy:AttachFileSchoolExpProxy):void
		{
			trace("onProgressUpload: " + proxy.bytesLoaded);			
		}
		
		private var fileInfo:SchoolExpFileUpLoadVO;
		
		private function onCompleteUpload(proxy:AttachFileSchoolExpProxy):void
		{
			trace("onCompleteUpload: " + proxy.fileVo.I_FILE_URL + "/" + proxy.fileVo.I_FILE_NAME);
			fileInfo = proxy.fileVo;
			if(Variables.company == "NOS") {
				//fileInfo.I_FILE_URL = fileInfo.I_FILE_URL.toUpperCase();
			}
			if(_bWaitingSave) {
				onClickRequest_proc();
			}
		}
		
		private function onFailedUpload(proxy:AttachFileSchoolExpProxy):void
		{
			trace("onFailedUpload: " + proxy.fileVo.I_FILE_NAME);
			Alert.show('파일업로드가 비정상종료 되었습니다.  '); 
			fileInfo = null;
		}
		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		*
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array
		{
			return [
					INIT_REQ_SCHOOLEXP,
					MODIFY_REQ_SCHOOLEXP,
					READONLY_REQ_SCHOOLEXP,
					AccountProxy.LOAD_ACCOUNTLIST_COMPLETE,
					AccountProxy.LOAD_ACCOUNTLIST_FAILED,
					FamilyProxy.LOAD_FAMILY_COMPLETE,
					FamilyProxy.LOAD_FAMILY_FAILED,
					SchoolExpProxy.SAVE_SCHOOLEXP_COMPLETE,
					SchoolExpProxy.SAVE_SCHOOLEXP_FAILED,
					SchoolExpProxy.LOAD_SCHOOLEXP_COMPLETE,
					SchoolExpProxy.LOAD_SCHOOLEXP_FAILED,
					
					AttachFileSchoolExpProxy.SELECTED_FILE,
					AttachFileSchoolExpProxy.COMPLETE_UPLOAD
					];
		}


		/**
		* Noti별로 처리한다.
		*
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			switch(note.getName())
			{
				case INIT_REQ_SCHOOLEXP:
					bActivated = true;
					initViewData(INIT_REQ_SCHOOLEXP);
					break;
				case MODIFY_REQ_SCHOOLEXP:
					bActivated = true;
					initViewData(MODIFY_REQ_SCHOOLEXP);
					loadDetailData(note.getBody() as String);
					break;
				case READONLY_REQ_SCHOOLEXP:
					bActivated = true;
					initViewData(READONLY_REQ_SCHOOLEXP);
					loadDetailData(note.getBody() as String);
					break;
				case SchoolExpProxy.LOAD_SCHOOLEXP_COMPLETE:
					setViewData(note.getBody() as SchoolExpProxy);
					break;
				case AccountProxy.LOAD_ACCOUNTLIST_COMPLETE:
					onLoadAccountData(note.getBody() as AccountProxy);
					break;
				case SchoolExpProxy.SAVE_SCHOOLEXP_COMPLETE:
					CommonAlert.showMessage("", "학자금 신청이 완료되었습니다.");
					facade.sendNotification(CLOSED_REQUEST_VIEW);

		 			view.fileList = new SchoolExpFileUpLoadVO();
		 			view.fileName = '';
		 			fileInfo = new SchoolExpFileUpLoadVO();
 								
					break;
				case AccountProxy.LOAD_ACCOUNTLIST_FAILED:
					CommonAlert.showMessage("", "계좌정보를 조회중 오류가 발생했습니다.");
					break;
				case SchoolExpProxy.SAVE_SCHOOLEXP_FAILED:
					CommonAlert.showMessage("", "("+SchoolExpProxy(note.getBody()).retCode+") " + SchoolExpProxy(note.getBody()).retText);
					//CommonAlert.showMessage("", "학자금 신청중 오류가 발생했습니다.");
					break;
					
				case AttachFileSchoolExpProxy.SELECTED_FILE:
					onSelectedFile();
					break;

				case AttachFileSchoolExpProxy.COMPLETE_UPLOAD:
					onCompleteUpload(note.getBody() as AttachFileSchoolExpProxy);
					break;
										
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}


		private function onLoadAccountData(proxy:AccountProxy):void
		{
			if(proxy.userAccountData.length>0) {
				view.account = proxy.userAccountData.getItemAt(0) as AccountVO;
			}
			else {
				CommonAlert.showMessage("", "계좌정보를 조회할 수 없습니다.");
			}
		}

		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():ReqSchoolExpView
        {
            return viewComponent as ReqSchoolExpView;
        }


	}
}